/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package izsla.filters;

import izsla.entities.TripUser;
import java.io.IOException;
import java.util.HashSet;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filter-based authorization.
 * @author aki
 */
public class AccessFilter implements Filter {
    /**Set of public pages.*/
    private HashSet<String> pubPages;

    public void init(FilterConfig filterConfig) throws ServletException {
	pubPages = new HashSet<String>();
	pubPages.add("/login.jsp");
	pubPages.add("/register.jsp");
        pubPages.add("/rss.jsp");
    }

    /**
     * Allows access only to public pages, if the user is not logged in, oterwise the user is redirected
     * to the login page.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	if(!(request instanceof HttpServletRequest)) {
	    chain.doFilter(request, response);
	}

	HttpServletRequest httpRequest = (HttpServletRequest)request;
	HttpServletResponse httpResp = (HttpServletResponse)response;
	TripUser user = null;

	try {
	    user = (TripUser)httpRequest.getSession().getAttribute("user");
	}
	catch(Exception e) {
	}

	System.out.println("Filtering\nURL=" + httpRequest.getRequestURL() + "\nURI=" + httpRequest.getRequestURI() + "\nServlet="  + httpRequest.getServletPath() + "\n");

	String servlet = httpRequest.getServletPath().toLowerCase();

	if(!servlet.endsWith(".jsf") && user == null && !pubPages.contains(servlet)) {
	    //RequestDispatcher dp = request.getRequestDispatcher("/login.jsf");
	    //dp.forward(request, response);
	    httpResp.sendRedirect("login.jsf");
	}

	chain.doFilter(request, response);
    }

    public void destroy() {
    }

}
